import Taro from '@tarojs/taro';
import {Image, View, Picker, Canvas, Textarea} from '@tarojs/components';
import {AtInput, AtTextarea} from 'taro-ui';
import {connect} from "@tarojs/redux";
import {request, unite} from '../../../utils/index';
import Xia from "../../../asset/myImages/xia.png";
import ImgAdd from "../../../asset/myImages/img_add.png";
import './addCourse.scss';


class MyCoupon extends Taro.Component {
    config = {
        navigationBarTitleText: '添加课程',
        backgroundColor: '#fff',
    };

    state = {
        cWidth: 0, //canvas宽
        cHeight: 0, //canvas高

        listResList: [], //课程列表
        nameId: '', //课程名称属性
        typeNameText: [], //课程名称
        typeNameTitle: [], //课程标签
        name: '请选择', //课程名称
        imgWrap: [], //课程图片数组
        count: 3, //图片最大张数
        typeName: '请选择', //课程类型
        zyzz: '', //课程效果/说明

        scaleNameWrap: [],
        scaleNameText: [],
        scaleName: '请选择', //规模
        money: '',
        attachId: '', //课程属性id
    };

    temp = {
        nextBtn: true,
    };

    componentDidMount() {
        const option = this.$router.params;
        if (option.id) {
            this.alertInit(option.id);
        }
        this.init();
    }

    //修改课程
    alertInit = (id) => {
        const params = {
            url: '/wx/coach/resClassRefDetail',
            data:{
                id,
            }
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    if (res && res.data) {
                        this.setState({
                            nameId: res.data.classId, //课程名称属性
                            typeNameTitle: res.data.labelNames, //课程标签
                            name: res.data.className, //课程名称
                            imgWrap: res.data.customAvatars, //课程图片数组
                            typeName: res.data.classTypeName, //课程类型
                            zyzz: res.data.describeInfo, //课程效果/说明
                            scaleName: res.data.classScaleName, //规模
                            // money: res.data.price,
                            attachId: res.data.classAttachId, //课程属性id
                        }, () => {
                            this.initNext();
                        })
                    }
                }
            }
        })
    };

    init = () => {
        const params = {
            url: '/wx/coach/listResClass',
            data:{}
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    if (res && res.data) {
                        let name = [];
                        res.data.forEach((item) => {
                            name.push(item.className);
                        });
                        this.setState({
                            typeNameText: name,
                            listResList: res.data,
                        })
                    }
                }
            }
        })
    };

    //选择课程名称
    onChangeType = (name, res) => {
        const {listResList, scaleNameWrap} = this.state;
        console.log(res);
        if(name == 'name') {
            this.setState({
                name: listResList[res.detail.value].className,
                typeName: listResList[res.detail.value].classTypeName,
                typeNameTitle: listResList[res.detail.value].labelNames,
                zyzz: listResList[res.detail.value].describeInfo,
                nameId: listResList[res.detail.value].classId,
                attachId: '',
                // money: '',
                scaleName: '请选择', //规模
                scaleNameWrap: [],
                scaleNameText: [],
            }, () => {
                this.initNext();
            });
        } else if (name == 'scaleName') {
            this.setState({
                scaleName: scaleNameWrap[res.detail.value].classScaleName,
                // money: scaleNameWrap[res.detail.value].price,
                attachId: scaleNameWrap[res.detail.value].classAttachId,
            })
        }
    };

    initNext = () => {
        const {nameId} = this.state;
        const params = {
            url: '/wx/coach/listResClassAttach?classId=' + nameId,
            data:{
                classId: nameId
            }
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    if (res && res.data) {
                        let name = [];
                        res.data.forEach((item) => {
                            name.push(item.classScaleName);
                        });
                        this.setState({
                            scaleNameWrap: res.data,
                            scaleNameText: name,
                        })
                    }
                }
            }
        })
    };

    //input内容保存
    datum = (name,val) => {
        this.setState({
            [name]: val
        })
    };

    //选择性别
    selectSex = (is) => {
        this.setState({
            sex: is
        })
    };

    //选择出生日期
    onChangeTimer = (name, value) => {
        let time = value.detail.value.replace(/-/g,".");
        this.setState({
            [name]: time //营业执照有效期
        });
    };

    //专业资质
    handleChange = (name, val) => {
        this.setState({
            [name]: val.detail.value
        })
    };

    onChangeImg = (files) => {
        this.setState({
            imgWrap: files
        })
    };

    addChooseImg = () => {
        const {imgWrap, count} = this.state;
        if(imgWrap.length < 3){
            if (!this.temp.nextBtn) return;  //防止多次点击
            this.temp.nextBtn = false;  //防止多次点击
            console.log(count + 'count');
            Taro.chooseImage({
                count: count, //上传张数为1
                sizeType: ['original'],
                sourceType: ['album'],
                success: (res) => {
                    for(let i = 0;i<res.tempFilePaths.length;i++) {
                        this.temp.nextBtn = true; //防止多次点击
                        //判断证件大于7M时不执行
                        if(res.tempFiles[i].size > 7340032) {
                            unite.showTipModal(`第${i+1}张图片太大了,请重传`);
                            continue
                        }

                        Taro.getImageInfo({
                            src: res.tempFilePaths[i],
                            success: (data) => {
                                //判断证件大小小于宽度并且为上传手持身份证照时执行, 否则压缩证件
                                if (res.tempFiles[i].size < 2097152) {
                                    this.addImgUrl(res.tempFilePaths[i]);
                                } else {
                                    let widthHeight = unite.imgZoom(data.width, data.height); //利用canvas压缩图片
                                    // let widthHeight = [data.width, data.height]; //利用canvas压缩图片
                                    //----------绘制图形并取出图片路径--------------
                                    this.setCanvas(widthHeight, res.tempFilePaths[i], i);  //Taro.canvasToTempFilePath   Canvas 在子组件中存在bug，所以提到父组件压缩
                                }
                            }
                        });
                    }
                },
                fail: () => {
                    this.temp.nextBtn = true; //防止重复点击
                }
            })
        }else{
            unite.showToast('最多只可添加3张图片')
        }
    };

    //压缩证件
    setCanvas = (widthHeight, value, i) => {
        const {cWidth, cHeight} = this.state;
        // Taro.showLoading({
        //     title: '图片压缩中...' //加载框
        // });
        let ctx = Taro.createCanvasContext('myCanvas', this.$scope);
        ctx.clearRect(0, 0, cWidth, cHeight); //清空画布
        this.setState({
            cWidth:widthHeight.canvasWidth, //赋值压缩后的宽度
            cHeight: widthHeight.canvasHeight //赋值压缩后的高度
        });
        ctx.drawImage(value, 0, 0, widthHeight.canvasWidth, widthHeight.canvasHeight);
        setTimeout(() => {
            ctx.draw(true, () => {
                Taro.canvasToTempFilePath({
                    canvasId: 'myCanvas',
                    destWidth: widthHeight.canvasWidth,
                    destHeight: widthHeight.canvasHeight,
                    quality: 0.2,
                    fileType:'jpg',
                    success: (datas) => {
                        this.addImgUrl(datas.tempFilePath);
                        console.log(JSON.stringify(datas.tempFilePath));
                    },
                    fail: () => {
                        unite.showTipModal(`第${i + 1}张图片上传失败,请重传`);
                    },
                    complete: (datas) => {
                        console.log(datas);
                    },
                })
            });   //留一定的时间绘制canvas
            // clearTimeout(clear);
        }, 1000);
    };

    //上传图片
    addImgUrl = (url) => {
        const {userToken} = this.props;
        Taro.uploadFile({
            url: 'https://pro.pmad.com.cn/api/wx/coach/uploadClassAvatar',
            filePath: url,
            name: 'avatarfile',
            fileType: 'image',
            accessToken: userToken,
            formData: {
                accessToken: userToken,
                avatarfile: url
            },
            success: (ret) => {
                let data = ret.data ? JSON.parse(ret.data) : {};
                console.log(JSON.stringify(ret))
                if (data.code == 200) {
                    if (data.data.indexOf('http') != -1) {
                        this.setState((pervState) =>({
                            count: pervState.count - 1,
                            imgWrap: pervState.imgWrap.concat(data.data),
                        }), () => {
                            console.log(JSON.stringify(this.state.imgWrap))
                        });
                    } else {
                        unite.showToast(data.data)
                    }
                } else {
                    unite.showToast('图片错误请重新上传')
                }
            },
            fail: (e) => {
                console.log(e);
            }
        });
    };

    //点击删除图片
    deleteImg = (value) => {
        // unite.showToast('目前暂不支持删除');
        const {imgWrap} = this.state;
        imgWrap.splice(value,1);
        this.setState((pervState) =>({
            count: pervState.count + 1,
            imgWrap,
        }));
    };

    statusName = () => {
        const {scaleNameText} = this.state;
        if (scaleNameText.length == 0) {
            unite.showToast('请先选择课程名称,或该课程暂无规模');
        }
    };

    sumbit = () => {
        const option = this.$router.params;
        const {nameId, name, typeName, zyzz, typeNameTitle, scaleName, money, imgWrap, attachId} = this.state;
        if (imgWrap.length == 0) return unite.showToast('请上传图片');
        if (name == '请选择') return unite.showToast('请选择课程名称');
        if (!zyzz) return unite.showToast('请输入课程效果/说明');
        if (scaleName == '请选择') return unite.showToast('请选择课程规模');
        if (!money) return unite.showToast('请输入价格');
        let params = {};
        if (option.id) {
            params = {
                url: '/wx/coach/updateResClassRef',
                data:{
                    classId: nameId, //课程ID
                    classAttachId: attachId, //课程属性ID
                    customAvatars: imgWrap, //自定义课程图片
                    classRefId: option.id, //ID，新增的时候为空，修改的时候不为空
                    price: money,
                    dispatchDesc: zyzz,
                }
            };
        } else {
            params = {
                url: '/wx/coach/addResClassRef',
                data:{
                    classId: nameId, //课程ID
                    classAttachId: attachId, //课程属性ID
                    customAvatars: imgWrap, //自定义课程图片
                    classRefId: '', //ID，新增的时候为空，修改的时候不为空
                    price: money,
                    dispatchDesc: zyzz,
                }
            };
        }
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    unite.showToast(option.id? '保存成功' : '添加成功');
                    setTimeout(() => {
                        Taro.navigateBack({delta: 1})
                    }, 2000)
                }
            }
        })
    };

    deleteKc = () => {
        Taro.showModal({
            title: '提示',
            content: '是否删除该课程?',
            success: (ress) => {
                if (ress.cancel) {
                } else {
                    const option = this.$router.params;
                    const params = {
                        url: '/wx/coach/removeResClassRef',
                        data:{
                            id: option.id
                        }
                    };
                    request(params).then(res => {
                        if (res) {
                            if(res.code == 200) {
                                unite.showToast('删除成功');
                                setTimeout(() => {
                                    Taro.navigateBack({delta: 1})
                                }, 1500)
                            }
                        }
                    })
                }
            },
        });
    };

    render() {
        const {name, typeName, scaleName, zyzz, imgWrap, money, typeNameText,typeNameTitle,
            scaleNameText, cWidth, cHeight} = this.state;
        const option = this.$router.params;
        return (
            <View className="myPage">
                <View className="apply-list-wrap">
                    <View className="apply-list-text">课程图片</View>
                    <View className="flex-l apply-list-img">
                        {imgWrap.map((item, index) => (
                            <View className="select-img-wrap">`
                                <View className="close-img flex-center" onClick={this.deleteImg.bind(this, index)}>x</View>
                                <Image mode="widthFix" key={index} className="select-img" src={item}/>
                            </View>
                        ))}
                        {imgWrap.length < 3 && (
                            <Image mode="widthFix" onClick={this.addChooseImg} className="select-img" src={ImgAdd}/>
                        )}
                    </View>
                </View>
                <View className="apply-list-wrap">
                    <View className="list-item flex-lr">
                        <View className="flex-top-l">
                            <View>课程名称</View>
                        </View>
                        <View className="flex-r">
                            <Picker className={`picker ${name === '请选择' ? 'picker-color' : ''}`} range={typeNameText} onChange={this.onChangeType.bind(this, 'name')}>
                                <View>
                                    {name}
                                </View>
                            </Picker>
                            <Image mode="widthFix" className="right-icon" src={Xia}/>
                        </View>
                    </View>
                    <View className="list-item flex-lr borderTop">
                        <View className="flex-top-l">
                            <View>课程类型</View>
                        </View>
                        <View className="flex-r flex-type-name">
                            {typeName}
                        </View>
                    </View>
                </View>
                <View className="apply-list-wrap">
                    <View className="apply-list-text">课程效果/说明</View>
                    <Textarea
                        value={zyzz}
                        className="insText"
                        auto-height
                        onChange={this.handleChange.bind(this, 'zyzz')}
                        onBlur={this.handleChange.bind(this, 'zyzz')}
                        onInput={this.handleChange.bind(this, 'zyzz')}
                        count={false}
                        placeholder='请输入'
                        maxlength={-1}
                    />
                    <View className="flex-l apply-list-bq">
                        <View>标签</View>
                        {typeNameTitle.map((item, index) => (
                            <View className="apply-list-item" key={index}>{item}</View>
                        ))}
                        {/*<Image mode="widthFix" className="add-select-img" src={ImgAdd}/>*/}
                    </View>
                </View>
                <View className="apply-list-wrap">
                    <View className="list-item flex-lr">
                        <View className="flex-top-l">
                            <View>规模</View>
                        </View>
                        {scaleNameText.length == 0 ? (
                            <View className="flex-r" onClick={this.statusName}>
                                <View>
                                    {scaleName}
                                </View>
                                <Image mode="widthFix" className="right-icon" src={Xia}/>
                            </View>
                        ) : (
                            <View className="flex-r">
                                <Picker className={`picker ${scaleName === '请选择' ? 'picker-color' : ''}`} range={scaleNameText} onChange={this.onChangeType.bind(this, 'scaleName')}>
                                    <View>
                                        {scaleName}
                                    </View>
                                </Picker>
                                <Image mode="widthFix" className="right-icon" src={Xia}/>
                            </View>
                        )}
                    </View>
                    <View className="list-item flex-lr borderTop">
                        <View className="flex-top-l">
                            <View>价格</View>
                        </View>
                        <View className="flex-r flex-type-name">
                            <AtInput
                                border={false}
                                style="width: 80%;"
                                className="ins"
                                name='realName'
                                type='text'
                                placeholder='请输入价格'
                                value={money}
                                onChange={this.datum.bind(this, 'money')}
                                onBlur={this.datum.bind(this, 'money')}
                            />
                        </View>
                    </View>
                </View>
                {option.id ? (
                    <View className="detail-btn-wrap flex-lr">
                        <View className="alert-btn alert-btn-active flex-center" onClick={this.deleteKc}>删除</View>
                        <View className="alert-btn flex-center" onClick={this.sumbit}>保存</View>
                    </View>
                ) : (
                    <View className="apply-btn flex-center" onClick={this.sumbit}>确定</View>
                )}
                <Canvas canvasId="myCanvas" style={`width: ${cWidth}px; height: ${cHeight}px; position: absolute; left:-10000px; top:-10000px; z-index: -100`}/>
            </View>
        )
    }
}

const mapStateToProps = state => {
    let {userToken} = state;
    return {
        userToken
    }
};

const mapDispatchToProps = {
};

export default connect(mapStateToProps, mapDispatchToProps)(MyCoupon);



